package models.instockandreturn

import java.sql.Timestamp

import javax.inject.Inject
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import scala.concurrent.{ExecutionContext, Future}

class InstockAndReturnRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext)
  extends HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  private class InStockAndReturnTable(tag: Tag) extends Table[InStockAndReturn](tag, "STOCK_PURCHASEORDER") {
    def id = column[Option[Int]]("id".toUpperCase, O.PrimaryKey, O.AutoInc)

    def eid = column[Int]("eid".toUpperCase) // 1:Instock , 2:PurReturn
    def kdFStockId = column[Int]("FStockId".toUpperCase) //  #
    def kdFStockNo = column[String]("FStockNo".toUpperCase)

    def modifyDatetime = column[Timestamp]("modifyDatetime".toUpperCase)

    def kdFBillNo = column[String]("KDFBillNo".toUpperCase)

    def kdDatetime = column[Timestamp]("KDDatetime".toUpperCase)

    def gyFBillNo = column[String]("GYFBillNo".toUpperCase)

    def gyDatetime = column[Timestamp]("GYDatetime".toUpperCase)

    def complete = column[Int]("complete".toUpperCase) //   # 状态：0，初始；1，写入管易；2，管易审核；3，管易出入库；4，管易出入库审核；5，回写金蝶；6，金蝶审核；7，
    def note = column[String]("note".toUpperCase)

    def kdMaterialID = column[String]("MaterialID".toUpperCase)

    def mustQt = column[Int]("mustQt".toUpperCase)

    def realQty = column[Int]("realQty".toUpperCase)

    def price = column[Double]("price".toUpperCase)

    def * = (id, eid, kdFStockId, kdFStockNo, modifyDatetime, kdFBillNo, kdDatetime, gyFBillNo, gyDatetime, complete, note, kdMaterialID, mustQt, realQty, price)
      .<>((InStockAndReturn.apply _).tupled, InStockAndReturn.unapply)
  }

  private val inStockAndReturnTable = TableQuery[InStockAndReturnTable]

  def findBy(gyFBillNo: String = "", complete: Int = 0) = db.run {
    inStockAndReturnTable
      .filterIf(gyFBillNo != "")(_.gyFBillNo === gyFBillNo)
      .filterIf(complete != 0)(_.complete === complete)
      .map(f => f).result
  }

  def updateComplete(complete: Int, id: Option[Int] = None, kdFStockNo: String = "", gyFBillNo: String = "") = db.run {
    inStockAndReturnTable
      .filterIf(gyFBillNo != "")(_.gyFBillNo === gyFBillNo)
      .filterIf(kdFStockNo != 0)(_.kdFStockNo === kdFStockNo)
      .filterOpt(id)(_.id === _)
      .map(f => f.complete).update(complete)
  }

  def insert(ins: InStockAndReturn) = db.run {
    inStockAndReturnTable.filter(_.kdFBillNo === ins.kdFBillNo).result
  }.flatMap { r =>
    if (r.nonEmpty) Future(r.head.id)
    else db.run(inStockAndReturnTable returning inStockAndReturnTable.map(_.id) += ins)
  }

}
